/** @odoo-module **/
let make_add_function = () => {
    let id = 1;
    return () => {
        return `virtual_${id++}`;
    }
};

const formatId = (id) =>{
    id = id+'';
    if(id.trim() == ''){
      return ''
    }else if(id.startsWith('virtual_')){
        return id.trim();
    }else if(!isNaN(Number(id))){
        id = Number(id);
        return id;
    }else{
        return id;
    }
};

const formatDate = (date,format) => {
    try {
        let dateArr = {
            'y+': date.getFullYear(),
            'm+': date.getMonth() + 1,
            'd+': date.getDate(),
            'H+': date.getHours(),
            'M+': date.getMinutes(),
            'S+': date.getSeconds(),
        }
        for (let i in dateArr) {
            let re = new RegExp('(' + i + ')');
            format = format.replace(re, () => dateArr[i] < 10 ? '0' + dateArr[i] : dateArr[i]);
        }
        return format
    }catch(e){
        return ''
    }
};

const formatPrice = (price) => {
    price = '' + price;
    price = price
        .replace(/\s*/g,"") //去除字符串内所有的空格
        .replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
        .replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
        .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); // 只能输入两个小数
    // if (price.indexOf('.') < 0 && price != '') {
    //     // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
    //     price = parseFloat(price);
    // }
    // if (price[0] == '0' && price != '') {
    //     // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
    //     price = parseFloat(price);
    // }
    if(price != ''){
        price = Number(price);
    }
    return price;
};

const keepTwoDecimal = (num) =>{
    if(num+''.trim() == ''){
        return ''
    };
    num = Number(num) || 0;
    let result = parseFloat(num);
    result = Math.round(num*100)/100;
    return result;
}

const add_material_item_id = make_add_function();
const add_material_item_bom_unit_ratio_id = make_add_function();
const add_number_category_id  = make_add_function();
const add_dish_bom_id  = make_add_function();
const add_dish_key_id  = make_add_function();
const add_apply_lines_id  = make_add_function();

const add_plan_day_cost_id = make_add_function();
const add_plan_day_record_show_id = make_add_function();
const add_net_material_id = make_add_function();

const add_dish_weight_price_id = make_add_function();
const add_site_stock_record_id = make_add_function();
const add_stock_out_record_detail_id = make_add_function();

const copiesNumber = (num) => {
    num = Math.ceil(num)
    if(num == 0 || num < 10) return Math.ceil(num)

    if(num < 100){
        let lastNumber = String(num)[String(num).length - 1]
        if(Number(lastNumber) > 5){
            num = num - Number(lastNumber) + 10
        }else if(Number(lastNumber) != 0){
            num = num - Number(lastNumber) + 5
        }
        return num
    }
    const numArr = String(num).split("")
    // 获取最后一位数字
    const lastNumber = numArr[numArr.length - 1]
    let newNumber;

    // console.log(lastNumber)
    if(Number(lastNumber) >= 5){
        numArr[numArr.length - 1] = 0
        // 0有两种含义 一种为十进一 一种为原本就是0
        // 上一次做了进位操作设置true 没做进位操作设置false
        // 默认为true
        let operation = true
        for(let i = numArr.length - 2; i >= 0; i--){
            //
            if(operation){

                if(Number(numArr[i]) + 1 == 10){
                    numArr[i] = 0
                    operation = true
                }else{
                    numArr[i] = Number(numArr[i]) + 1
                    operation = false
                }
            }
        }
        if(operation) numArr.unshift(1)
    }else{
        numArr[numArr.length - 1] = 0

    }
    newNumber = numArr.join("")
    // console.log(newNumber)
    return Number(newNumber)
}
const changeObjKey = (obj,pre) => {
    let newObj = {};
    for(let key in obj){
        newObj[pre+'_'+key] = obj[key];
    }
    return newObj;
};
const toObj = (arr,k) => {
    let _Obj = {};
    for(let i = 0; i　< arr.length; i++) {
        _Obj[arr[i][k]] = arr[i];
    }
    return _Obj;
};
// 数组是否有重复值
const arryIsRepeat = (arr) =>{
    let hash = {};
    for (let i in arr) {
        if (hash[arr[i]]) {
            //hash 哈希
            return true;
        }
        hash[arr[i]] = true;
    }
    return false;
}

//全屏
const fullScreen = () => {
    const element = document.documentElement; //若要全屏页面div
    // const element = document.querySelector(".fullScreen_panorama");
    //IE 10及以下ActiveXObject
    if (window.ActiveXObject) {
        const WsShell = new ActiveXObject('WScript.Shell');
        WsShell.SendKeys('{F11}');
        //写全屏后的执行函数
    }
    //HTML W3C 提议
    else if (element.requestFullScreen) {
        element.requestFullScreen();
        //写全屏后的执行函数
    }
    //IE11
    else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
        //写全屏后的执行函数
    }
    // Webkit (works in Safari5.1 and Chrome 15)
    else if (element.webkitRequestFullScreen) {
        element.webkitRequestFullScreen();
        //写全屏后的执行函数
    }
    // Firefox (works in nightly)
    else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
        //写全屏后的执行函数
    } else {
        alert("此设备不支持 Fullscreen API")
    }

}

//退出全屏
const fullExit = () => {
    const element= document.documentElement;//若要全屏页面中
    // const element = document.querySelector(".fullScreen_panorama");
    //IE ActiveXObject
    if (window.ActiveXObject) {
        const WsShell = new ActiveXObject('WScript.Shell');
        WsShell.SendKeys('{F11}');
        //写退出全屏后的执行函数
    }
    //HTML5 W3C 提议
    else if (element.requestFullScreen) {
        document.exitFullscreen();
        //写退出全屏后的执行函数
    }
    //IE 11
    else if (element.msRequestFullscreen) {
        document.msExitFullscreen();
        //写退出全屏后的执行函数
    }
    // Webkit (works in Safari5.1 and Chrome 15)
    else if (element.webkitRequestFullScreen) {
        document.webkitCancelFullScreen();
        //写退出全屏后的执行函数
    }
    // Firefox (works in nightly)
    else if (element.mozRequestFullScreen) {
        document.mozCancelFullScreen();
        //写退出全屏后的执行函数
    }
}

const onFullscreenChange=(fn)=>{
    document.addEventListener('fullscreenchange', function(e){ /*code*/fn(e) });
    document.addEventListener('webkitfullscreenchange', function(e){ /*code*/fn(e)});
    document.addEventListener('mozfullscreenchange', function(e){ /*code*/fn(e)});
    document.addEventListener('MSFullscreenChange', function(e){ /*code*/fn(e)});
}

const dinnerTypeCategoryComparator = (d1,d2) => {
    let getNum = (v)=>{
        let num = v == 'dn2'?2:v=='dn3'?3:v=='dn5'?5:v=='dn1'?1:6;
        return num;
    };
    let d1Number = getNum(d1.dinner_type);
    let d2Number = getNum(d2.dinner_type);
    if(d1Number == d2Number){
        d1Number = d1.dt_no;
        d2Number = d2.dt_no;
    }
    return d1Number - d2Number;
};
const arrayRemoveRepeat = (array)=>{
    return Array.from(new Set(array));
}

const isChineseStr = (str) => {
    return /^[\u4E00-\u9FA5]+$/.test(str)
}

const Uint8ArrayToString = (fileData) =>{
    let dataString = "";
    for (let i = 0; i < fileData.length; i++) {
        dataString += String.fromCharCode(fileData[i]);
    }

    return dataString
}


const stringToUint8Array = (str) => {
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
    }

    let tmpUint8Array = new Uint8Array(arr);
    return tmpUint8Array
}

const decompressData = (gzip) =>{
    let v_data = stringToUint8Array(gzip);
    let d_data = pako.ungzip(v_data);
    let s = Uint8ArrayToString(d_data);
    let data = JSON.parse(s);
    return data;
}
const is_same_manual_material_qty = (arr1,arr2) =>{
    if(arr1.length != arr2.length){
        return false;
    }
    let flag = true;
    arr1.forEach((v,i)=>{
        let {material_id,material_qty,process_id,unit_id} = v;
        if(arr2[i].material_id != material_id){
            flag = false;
        }
        if(arr2[i].material_qty != material_qty){
            flag = false;
        }
        if(arr2[i].process_id != process_id){
            flag = false;
        }
        if(arr2[i].unit_id != unit_id){
            flag = false;
        }
    });
    return flag;
};
const is_same_chef_ids = (arr1,arr2) =>{
    try {
        let flag = arr1.join('|') == arr2.join('|');
        return flag;
    }catch (e) {
        return false
    }

};


export {
    arrayRemoveRepeat,
    arryIsRepeat,
    toObj,
    changeObjKey,
    keepTwoDecimal,
    formatPrice,
    formatDate,
    formatId,
    add_material_item_id,
    add_material_item_bom_unit_ratio_id,
    add_number_category_id,
    add_dish_bom_id,
    add_dish_key_id,
    add_apply_lines_id,
    add_plan_day_cost_id,
    add_plan_day_record_show_id,
    add_net_material_id,
    add_dish_weight_price_id,
    add_site_stock_record_id,
    add_stock_out_record_detail_id,
    onFullscreenChange,
    fullScreen,
    fullExit,
    dinnerTypeCategoryComparator,
    isChineseStr,
    decompressData,
    is_same_manual_material_qty,
    is_same_chef_ids
}
